<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        /**
         * defineProperty 1.创建一个可控的对象  2.修改一个对象 为可控制对象
         *  Object.defineProperty()
         * configurable
         * enumerable
         * 
          */
        //  第一种方式
        var val = '张三'
        var obj = Object.defineProperty({},'name',{
            get: function() {
                return val;
            },
            set: function(newval) {
                if (val !==newval) val = newval;
            },
            configurable: true,
            enumerable: true
        })
        console.log(obj);
        // 第二种方式
        var obj2 = {
            name: '张三',
            age: 18
        }
        function observe(obj1) {
            for (var key in obj1) {
                (function () { 
                    var val = obj1[key];
                    console.log(val);
                    if (obj1.hasOwnProperty(key)) {
                        Object.defineProperty(obj1,key,{
                            get: function() {
                                console.log('get');
                                return val;
                            },
                            set: function(newvalue) {
                                if (val !== newvalue) val = newvalue;
                            },
                            configurable: true,
                            enumerable: true
                        })
                    }
                })()
            }
        }
        observe(obj2);
        obj2.name = '李四';
        obj2.age = 20;
        console.log(obj2);
    </script>
</body>
</html>